package org.devocean.groupbuying.service.impl;

import java.util.List;

import org.devocean.groupbuying.dao.DiscountDAO;
import org.devocean.groupbuying.domain.Discount;
import org.devocean.groupbuying.service.DiscountService;
import org.devocean.groupbuying.service.ExploredService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DiscountServiceImpl implements DiscountService {

	@Autowired
	private DiscountDAO discountDAO;

	@Autowired
	private ExploredService exploredService;

	@Transactional(readOnly = true)
	public Discount getDiscountById(Integer discountID) {

		return discountDAO.findDiscountById(discountID);
	}

	@Transactional
	public Discount addOrUpdateDiscount(Discount discount) {

		final Discount newDiscount;

		if (discount.getDiscountID() == null) {
			newDiscount = discountDAO.saveDiscount(discount);
		} else {
			newDiscount = discountDAO.updateDiscount(discount);
		}

		return newDiscount;
	}

	@Transactional
	public void removeDiscount(Integer discountID) {
		Discount discount = discountDAO.findDiscountById(discountID);
		if(discount != null && discount.getVoucher() == null ){
			discountDAO.deleteDiscount(discountID);
		}
		
	}

	public long countDiscounts() {

		return discountDAO.countDiscount();
	}

	@Transactional
	public List<Discount> getAllDiscounts() {
		return discountDAO.findAllDiscounts();
	}

	@Transactional
	public long countDiscountValidKeys(Integer discountID) {
		return discountDAO.countDiscountValidKeys(discountID);
	}

}
